package sessionBean;

import java.util.List;

import interfaceBeanRemote.sessionParticipationRemote;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import entityBean.Investisseur;
import entityBean.Participation;
import entityBean.Startup;

/**
 * Session Bean implementation class sessionParticipation
 */
@Stateless
public class sessionParticipation implements sessionParticipationRemote{

	@PersistenceContext(unitName = "EJB3_Entity")
	private EntityManager em;

	@PostConstruct
	public void init() {
		System.out.println("calling init method");
	}

	@PreDestroy
	public void cleanup() {
		System.out.println("calling cleanup method");
	}

	/**
	 * Default constructor.
	 */
	public sessionParticipation() {
		// TODO Auto-generated constructor stub
	}
	
	@Override
	public void addParticipation(Participation par) {
		// TODO Auto-generated method stub
		em.persist(par);
	}

	@Override
	public Participation findParticipation(int id) {
		// TODO Auto-generated method stub
		return em.find(Participation.class, id);
	}

	@Override
	public void removeParticipation(Participation par) {
		// TODO Auto-generated method stub
		if (findParticipation(par.getIdParticipation()) != null)
			em.remove(par);

	}

	@Override
	public void removeParticipationById(int id) {
		em.remove(em.find(Participation.class, id));
	}
	

	@Override
	public void updateParticipation(Participation par) {
		em.merge(par);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Participation> getParticipationListWithInvestisseur(int idStartUp) {
		// TODO Auto-generated method stub
		Query query = em.createQuery("SELECT p FROM Participation AS p inner join fetch p.investisseur"
				+ " WHERE p.startup = " + idStartUp + " ORDER BY p.idParticipation ASC");
		return query.getResultList();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Participation> getParticipationListWithInvestisseur2(int idInv) {
		// TODO Auto-generated method stub
		Query query = em.createQuery("SELECT p FROM Participation AS p inner join fetch p.startup"
				+ " WHERE p.investisseur.idInvestisseur = " + idInv + " ORDER BY p.idParticipation ASC");
		return query.getResultList();
	}
	
	@Override
	public void refresh(Participation p) {
		// TODO Auto-generated method stub
		em.refresh(p);
	}
	
	@Override
	public void flush() {
		// TODO Auto-generated method stub
		em.flush();
	}
	
	

}
